package com.defysoft.waukidsbus.start;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsbus.BaseActivity;
import com.defysoft.waukidsbus.Data_Type.BC_GOBUS;
import com.defysoft.waukidsbus.JsonParser;
import com.defysoft.waukidsbus.R;

public class Start_Select extends BaseActivity {
	Toolbar toolbar;
	GridView listView;
	ArrayList<BC_GOBUS> list;
	final int SUCCESS = 10;
	final int FAIR = 9;
	EditText et;
	StartAdapter startAdapter;
	private SharedPreferences login_code;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start__select);
		setStartData();
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		listView=(GridView)findViewById(R.id.START_SELECT_LIST);
		
		toolbar = (Toolbar) findViewById(R.id.START_SELECT_TOOL);
		et=(EditText)findViewById(R.id.SET_SCANTIME);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		startNetwork(1);
	}
	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		firstThread=new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			mainThread();	
			}
		});
		firstThread.start();
	}


	
	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: 
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case FAIR: 
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
			.show();
			break;
		case SUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			list=JsonParser.AttendSelectMember((String) _message.obj);
			startAdapter=new StartAdapter();
			listView.setAdapter(startAdapter);
			if(list.size()==1){				
				
				listView.setNumColumns(1);
				listView.setLayoutParams(new LinearLayout.LayoutParams((listView.getWidth()/2),
						listView.getHeight()));
			}else if (list.size()==2) {
				
				listView.setNumColumns(2);
			}else if (list.size()>=3) {
				
				
				listView.setNumColumns(3);
			}
			break;
		}
	}
	
	protected void mainThread() {
		// TODO Auto-generated method stub
				String msg = "";
				try {
					JSONObject jsonObject = new JSONObject(publicHttpCallback(
							HTTP_SELECT_START, "code="+login_code.getString("sch_code", null)));
					if (jsonObject.getBoolean("success")) {
						msg = jsonObject.getString("payload");
						onNetworkCallback(SUCCESS, msg);
					} else {
						onNetworkCallback(FAIR, jsonObject.getString("message"));
					}
				} catch (Exception e) {
					onNetworkCallback(CATCH_EXCEPTION, e.toString());
				};
	}
	
	class StartAdapter extends ArrayAdapter<String>{
		
		public StartAdapter() {
			super(Start_Select.this,0);
			// TODO Auto-generated constructor stub
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int pos=position;
			StartHolder startHolder;
			if(convertView==null){
				convertView=getLayoutInflater().inflate(R.layout.start_select_row, null);
	
				(convertView.findViewById(R.id.START_SELECT_LL))
						.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
								(int) ((listView.getHeight())*0.7)));
				startHolder=new StartHolder();
				startHolder.textView=(TextView)convertView.findViewById(R.id.START_SELECT_ROW);
				convertView.setTag(startHolder);
			}else {
				startHolder=(StartHolder)convertView.getTag();
			}
			startHolder.textView.setText(list.get(position).Gob_Name);
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder builder = new AlertDialog.Builder(Start_Select.this);
					builder.setMessage(list.get(pos).Gob_Name+" 버스를 선택하셨습니다.\n운행이 시작되면 부모님께 메시지가 전송 됩니다.").setCancelable(false)
							.setPositiveButton("운행시작", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									startActivity(new Intent(Start_Select.this, Start_ScanMode.class)
									.putExtra("code", list.get(pos).PK_Gob_Code+"")
									.putExtra("second", et.getText().toString())
									.putExtra("Gob_Name", list.get(pos).Gob_Name)//버스이름.
											);
								}
							})
							.setNegativeButton("취소", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();	
					
				}
			});
			return convertView;
		}	
	}
	
	class StartHolder{
		TextView textView;
	}
	
}
